/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DLL;

/**
 *
 * @author PyyPyLyn
 */
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JOptionPane;

public class ResponseFunction 
{
    public static boolean ResponseBroadcast(DatagramPacket recieved)
    {        
        boolean result = true;
        try
        {
            byte[] response = new byte[1024]; 
            response = PhanTichGoiTinYeuCau(recieved);
            if(response.length > 0)
            {
                result = SendFunction.SendDataPacket(new DatagramSocket(), recieved.getAddress(), response);  
            }                      
        }
        catch (Exception e)
        {
            return false;
        }
        return result;
    }
    
    public static byte[] PhanTichGoiTinYeuCau(DatagramPacket receivedData)
    {
        byte[] reBuf = new byte[1024];
        reBuf = receivedData.getData();
        byte flag = reBuf[0];
        byte[] lenghData = Arrays.copyOfRange(reBuf, 1, 5);
        //BufferedReader br = new BufferedReader
        int lData = ((lenghData[0] & 0xFF) << 24) | ((lenghData[1] & 0xFF) << 16)
        | ((lenghData[2] & 0xFF) << 8) | (lenghData[3] & 0xFF);
        byte[] seBuf = new byte[]{};
        if((char)flag == '1')
        {
            //Nhan duoc goi tin check chunk
            byte[] dataCheck = Arrays.copyOfRange(reBuf, 5,lData + 5);
            //Ten tap tin can tim
            String fileName = new String(dataCheck);
            //Flag response check chunk
            String seflag = "2";
            List<String> listFile = CommonMethods.CheckChunksExist(fileName);
            ///
            seBuf = QueryPackets.ResponNormal(seflag, listFile);
            
        }
        else if((char)flag == '3')
        {
            //Nhan Duoc Yeu Cau Ket Noi De DownLoad
            seBuf = Arrays.copyOfRange(reBuf, 1, reBuf.length);
            JOptionPane.showMessageDialog(null, "Da nhan goi tin yeu cau tai");
            
        }
        return seBuf;
    }
    
    public static List<String> PhanTichGoiTinPhanHoi(DatagramPacket receivedData)
    {
        byte[] reBuf = new byte[1024];
        reBuf = receivedData.getData();
        byte flag = reBuf[0];
        List<String> seData = new ArrayList<String>();
        byte[] seBuf = new byte[]{};
        byte[] lenghData = Arrays.copyOfRange(reBuf, 1, 5);
        //BufferedReader br = new BufferedReader
        int lData = ((lenghData[0] & 0xFF) << 24) | ((lenghData[1] & 0xFF) << 16)
        | ((lenghData[2] & 0xFF) << 8) | (lenghData[3] & 0xFF);
        if((char)flag == '2')
        {
            seBuf = Arrays.copyOfRange(reBuf, 5, lData+5);
            String sData = new String(seBuf);
            seData = Arrays.asList(sData.split(","));
            for (int i = 0; i < seData.size(); i++)
            {
                List<String> str = Arrays.asList(seData.get(i).split("\\."));
                seData.set(i, str.get(str.size() - 2));
            }
        }
        return seData;
    }
    
    public static ArrayList<byte[]> ResponseDownloadRequest(byte[] data)
    {        
        boolean result = true;
        ArrayList<byte[]> seData = new ArrayList<byte[]>();
        try
        {
            byte[] response = new byte[1024]; //kich thuoc goi tin gui di
            
            
            String sHeader = LayThongTinGoiTin(data);
           
            if(sHeader.equals(""))
            {
                return null;
            }
            //Cat lay port, ten file
            
            List<String> str = Arrays.asList(sHeader.split(","));
            String tenfile = str.get(0);
            int port = Integer.parseInt(str.get(1));
            
            int staticbytes = 17 + tenfile.getBytes().length;
            int bytes = 1024 - staticbytes;
            //Xu ly ten file
            File f = new File(System.getProperty("user.dir")+"/"+tenfile);
            if(f.exists())
            {
                 byte[] filebyte = CommonMethods.ConvertFileIntoByteArray(f);
                 seData = CommonMethods.SplitBytesToArrayByte(filebyte, bytes);
                 
            }                  
        }
        catch (Exception e)
        {
            //return false;
        }
        return seData;
    }
    public static String LayThongTinGoiTin(byte[] data)
    {
        String sHeader = "";
        byte[] reBuf = data;
        byte flag = reBuf[0];
        byte[] seBuf = new byte[]{};
        byte[] lenghData = Arrays.copyOfRange(reBuf, 1, 5);
        //BufferedReader br = new BufferedReader
        int lData = ((lenghData[0] & 0xFF) << 24) | ((lenghData[1] & 0xFF) << 16)
        | ((lenghData[2] & 0xFF) << 8) | (lenghData[3] & 0xFF);
        if((char)flag == '3')
        {
            seBuf = Arrays.copyOfRange(reBuf, 5, lData+5);
            sHeader = new String(seBuf);
        }
        return sHeader;
    }
    
    
    public static byte[] PhanTichDownload(DatagramPacket receivedData)
    {
        byte[] reBuf = new byte[1024];
        reBuf = receivedData.getData();
        
        byte[] seBuf = new byte[]{};
        byte flag = reBuf[0];
        if((char)flag == '0')
        {
            //Goi tin download
            //Short header length
            byte[] headerlength = Arrays.copyOfRange(reBuf, 1, 3);
            short valueHeaderlength = ByteBuffer.wrap(headerlength).order(ByteOrder.LITTLE_ENDIAN).getShort();
            //Short packet length
            byte[] packets = Arrays.copyOfRange(reBuf, 3, 5);
            short valuePackets = ByteBuffer.wrap(packets).order(ByteOrder.LITTLE_ENDIAN).getShort();
            //Integer CheckSum
            byte[] checksum = Arrays.copyOfRange(reBuf, 5, 9);
            int valueChecksum = ((checksum[0] & 0xFF) << 24) | ((checksum[1] & 0xFF) << 16)
                    | ((checksum[2] & 0xFF) << 8) | (checksum[3] & 0xFF);
            //Integer Sequence
            byte[] sequence = Arrays.copyOfRange(reBuf, 9, 13);
            int valuesequence = ((sequence[0] & 0xFF) << 24) | ((sequence[1] & 0xFF) << 16)
                    | ((sequence[2] & 0xFF) << 8) | (sequence[3] & 0xFF);
            //Integer Acknowledge
            byte[] acknowledge = Arrays.copyOfRange(reBuf, 13, 17);
            int valueacknowledge = ((acknowledge[0] & 0xFF) << 24) | ((acknowledge[1] & 0xFF) << 16)
                    | ((acknowledge[2] & 0xFF) << 8) | (acknowledge[3] & 0xFF);
            //String Header
            byte[] header = Arrays.copyOfRange(reBuf, 17, reBuf.length);
            String valueHeader = new String(headerlength);
            //ByteData
            byte[] data = Arrays.copyOfRange(reBuf, 17+reBuf.length, 1024);
            seBuf = data;
        }
        if((char)flag == '4')
        {
            //Goi tin tu choi download
            byte[] data = "4".getBytes();
            seBuf = data;
        }
        if((char)flag == '5')
        {
            //Goi tin stop and wait
            byte[] data = "5".getBytes();
            seBuf = data;
        }
        return seBuf;
    }
    
    // Ham phan tich goi tin trao doi ---> (tra ve) byte[] data
    // neu gap phai goi tin tu choi thi tra byte[0] = 1
    // stop and wait thi tra ve byte[0] = 1
    
}
